package cn.lqz.bucttrain.service.impl;

import cn.lqz.bucttrain.enums.ResponseCodeEnum;
import cn.lqz.bucttrain.exceptions.BaseException;
import cn.lqz.bucttrain.service.DataBaseService;
import cn.lqz.bucttrain.utils.DataBaseUtils;
import cn.lqz.bucttrain.utils.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

@Slf4j
@Service
public class DataBaseServiceImpl implements DataBaseService {
    /**
     * 默认备份文件夹
     */
    @Value("${service.database.default-folder}")
    private String defaultFolder;
    @Resource
    private DataBaseUtils dataBaseUtils;
    /**
     * 数据库备份在服务器上
     * @param folderPath
     */
    @Override
    public void backupServer(String folderPath) {
        log.info("数据库在服务器上进行备份：folderPath={}",folderPath);
        if (StringUtils.isEmpty(folderPath)){
            folderPath = defaultFolder;
        }
        File folder = new File(folderPath);
        if (!folder.exists()){
            folder.mkdirs();
        }
        try{
            Boolean success = dataBaseUtils.dbBackUp(folderPath);
            if (!success){
                throw new BaseException(ResponseCodeEnum.CODE_500.getCode(),"数据库备份失败");
            }
        }catch (Exception e){
            throw new BaseException(ResponseCodeEnum.CODE_500.getCode(),"数据库备份失败");
        }
    }

    /**
     * 数据库备份到本地
     * @param httpServletResponse
     */
    @Override
    public void backupLocal(HttpServletResponse httpServletResponse) {
        log.info("数据库备份到本地");
        File folder = new File(defaultFolder);
        if (!folder.exists()){
            folder.mkdirs();
        }
        try(OutputStream outputStream = httpServletResponse.getOutputStream();){
            File file = dataBaseUtils.dbBackUpReturnFile(defaultFolder);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            fileInputStream.close();
            file.delete();
        }catch (Exception e){
            throw new BaseException(ResponseCodeEnum.CODE_500.getCode(),"数据库备份失败");
        }
    }
}
